﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Reflection;

namespace ConsoleApplication
{
    public class EntityDemo
    {
        public EntityDemo() { }

        public void GetB(Entity.A aEntity)
        {
            Type aType = aEntity.GetType();
            foreach (System.Reflection.PropertyInfo item in aType.GetProperties())
            {
                if (item.PropertyType.Name.Substring(0, 5) == "IList")
                {
                    System.Collections.IList list = (System.Collections.IList)item.GetValue(aEntity, null);
                    item.SetValue(aEntity, GetEntity(list, aEntity), null);
                }
            }
        }
        public object GetEntity(System.Collections.IList list, Entity.IBaseEntity entityFather)
        {
            object returnObj = null;
            Entity.IBaseEntity baseEntity = null;
            if (list != null)
            {
                Type type = list.GetType();
                string strName = type.FullName;
                strName = strName.Substring(strName.IndexOf("[[") + 2);
                strName = strName.Substring(0, strName.Length - 2);
                string[] strType = strName.Split(',');
                System.Reflection.Assembly assem = System.Reflection.Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + strType[1].Trim() + ".dll");
                baseEntity = (Entity.IBaseEntity)assem.CreateInstance(strType[0].Trim());
                Type bType = baseEntity.GetType();
                if (bType.GetProperty(entityFather.PK) == null)
                {
                    return null;
                }
                bType.GetProperty(entityFather.PK).SetValue(baseEntity, entityFather.PKValue, null);

                System.Reflection.MethodInfo[] mis = bType.GetMethods(BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance);
                MethodInfo mi = null;
                foreach (MethodInfo item in mis)
                {
                    if (item.Name == "GetObjectList")
                    {
                        mi = item;
                        break;
                    }
                }
                returnObj = mi.Invoke(baseEntity, new object[] { "Hi" });
            }
            return returnObj;
        }

        public static void Start()
        {
            EntityDemo demo = new EntityDemo();
            Entity.A aEntity = new Entity.A();
            aEntity.PKValue = "AA";
            demo.GetB(aEntity);
        }

    }
}
